<template>
    <el-card>
        <el-form :inline="true" class="form">
            <el-form-item label="连接名称搜索">
                <el-input placeholder="请你输入连接名称搜索关键字" v-model="connNameLike"></el-input>
            </el-form-item>
            <el-form-item label="数据库名称搜索">
                <el-input placeholder="请你输入数据库名称搜索关键字" v-model="datasourceLike"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="search">搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0px;">
        <el-button type="primary" size="default" icon="Plus" @click="addDatasource">添加数据源连接</el-button>
        <el-table border style="margin: 10px 0px;" :data="allDatasource">
            <el-table-column type="index" align="center" label="#"></el-table-column>
            <el-table-column label="连接名" align="center" prop="connName"></el-table-column>
            <el-table-column label="数据库名称" align="center" prop="datasource" show-overflow-tooltip></el-table-column>
            <el-table-column label="数据库类型" align="center" show-overflow-tooltip>
                <template #="{row,$index}">
                    <el-button type="primary" plain> {{row.dbType}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="环境名称" align="center" show-overflow-tooltip>
                <template #="{row,$index}">
                    <el-button type="warning" plain> {{row.environment}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="是否连接成功" align="center" show-overflow-tooltip>
                <template #="{row,$index}">
                    <el-button :type=setStatusButton(row) plain> {{row.isOkStr}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280px" align="center">
                <!-- row:已有的职位对象 -->
                <template #="{ row, $index }">
                    <el-button type="primary" size="small" icon="InfoFilled" @click="findInfo(row)">详情</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateDatasource(row)" v-if="row.isOk == '0'">编辑</el-button>
                    <el-button type="primary" size="small" icon="CaretRight" @click="testConnect(row.uuid)" v-if="row.isOk == '0'">测试连接</el-button>
                    <el-button type="primary" size="small" icon="Document" @click="genWordDatasource(row.uuid)" v-if="row.isOk == '1'">生成文档</el-button>
                    <el-popconfirm :title="`你确定要同步${row.connName}数据?`" width="260px" @confirm="syncData(row.uuid)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Refresh">同步</el-button>
                        </template>
                    </el-popconfirm>
                    <el-popconfirm :title="`你确定要删除${row.connName}?`" width="260px" @confirm="delDatasource(row.uuid)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
                       :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="items"
                       @current-change="getHasDatasource"
                       @size-change="sizeChange"/>
    </el-card>
    <!-- 添加职位与更新已有职位的结构:对话框 -->
    <el-dialog v-model="dialogVisite" :title="datasourceAddOrUpdateForm.uuid ? '更新连接' : '添加连接'">
        <el-form label-width="120px" :model="datasourceAddOrUpdateForm" :rules="rules" ref="form">
            <el-form-item label="连接名称" prop="connName">
                <el-input placeholder="请你输入连接名称" v-model="datasourceAddOrUpdateForm.connName"></el-input>
            </el-form-item>
            <el-form-item label="连接Url" prop="connUrl">
                <el-input placeholder="请你输入连接Url" v-model="datasourceAddOrUpdateForm.connUrl"></el-input>
            </el-form-item>
            <el-form-item label="数据库类型" prop="dbType">
                    <el-select v-model="datasourceAddOrUpdateForm.dbType" placeholder="请选择数据库类型">
                        <el-option
                                v-for="item in dbTypeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        />
                    </el-select>
            </el-form-item>
            <el-form-item label="环境" prop="environment">
                <el-input placeholder="请你输入环境" v-model="datasourceAddOrUpdateForm.environment"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input placeholder="请你输入用户名" v-model="datasourceAddOrUpdateForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input placeholder="请你输入密码" v-model="datasourceAddOrUpdateForm.password"></el-input>
            </el-form-item>
            <el-form-item label="数据库名称" prop="datasource">
                <el-input placeholder="请你输入数据库名称" v-model="datasourceAddOrUpdateForm.datasource"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" size="default" @click="dialogVisite = false">取消</el-button>
            <el-button type="primary" size="default" @click="save">确定</el-button>
        </template>
    </el-dialog>


    <!-- 生成文档 对话框 -->
    <el-dialog v-model="dialogDoc" :title="生成数据库文档">
        <el-form label-width="120px" :model="docGenForm" :rules="rules" ref="form">
            <el-form-item label="生成到本地地址" prop="address">
                <el-input placeholder="请你输入地址" v-model="docGenForm.address"></el-input>
            </el-form-item>
            <el-form-item label="用户类型:">
                <el-select v-model="docGenForm.docType" placeholder="请选择模板类型">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" size="default" @click="dialogDoc = false">取消</el-button>
            <el-button type="primary" size="default" @click="genWord">确定</el-button>
        </template>
    </el-dialog>

    <el-drawer v-model="drawer" size="700" >
        <!-- 标题部分 -->
        <template #header>
            <h4>查看连接的详情</h4>
        </template>
        <template #default>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">连接名</el-col>
                <el-col :span="18">{{ datasourceInfo.connName }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">数据库类型</el-col>
                <el-col :span="18">{{ datasourceInfo.dbType }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">环境名</el-col>
                <el-col :span="18">{{ datasourceInfo.environment }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">连接url</el-col>
                <el-col :span="18">{{ datasourceInfo.connUrl }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">数据库名</el-col>
                <el-col :span="18">{{ datasourceInfo.datasource }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">是否测试通过</el-col>
                <el-col :span="18">{{ datasourceInfo.isOkStr }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">用户名</el-col>
                <el-col :span="18">{{ datasourceInfo.username }}</el-col>
            </el-row>
            <el-row style="margin:10px 0px;">
                <el-col :span="6">密码</el-col>
                <el-col :span="18">{{ datasourceInfo.password }}</el-col>
            </el-row>

        </template>
    </el-drawer>
</template>

<script setup lang="ts">
    import {nextTick, onMounted, reactive, ref} from 'vue';
    //请求方法
    import type {RoleData} from '@/api/acl/role/type'
    //引入骨架的仓库
    import useLayOutSettingStore from '@/store/modules/setting';
    import {ElMessage} from 'element-plus';
    import {reqAddOrUpdateRole} from "@/api/business/role";
    import {HandleResponseData, UuidForm, UuidsForm} from "@/api/common/type";
    import {
        reqAddOrUpdateDatasource,
        reqBatchDelDatasource, reqDatasourceGenWord,
        reqDatasourceInfo,
        reqDatasourcePageList, reqDatasourceSync,
        reqDatasourceTestConnect
    } from "@/api/sys/datasource";
    import {
        DatasourceInfo,
        DatasourceInfoReponseData,
        DatasourceListReponseData,
        DatasourceAddOrUpdateForm, DocGenForm
    } from "@/api/sys/datasource/type";
    import {reqCloseUser} from "@/api/business/user";

    let settingStore = useLayOutSettingStore();
    //当前页码
    let page = ref<number>(0);
    //一页展示几条数据
    let pageSize = ref<number>(10);
    //搜索角色关键字
    let connNameLike = ref<string>('');
    let datasourceLike = ref<string>('');
    let datasourceInfo = ref<DatasourceInfo>({});
    //存储全部已有的职位
    let allDatasource = ref<DatasourceInfo[]>([]);
    //职位总个数
    let items = ref<number>(0);
    //控制对话框的显示与隐藏
    let dialogVisite = ref<boolean>(false);
    let dialogDoc = ref<boolean>(false);
    let uuidsFrom = reactive<UuidsForm>({
        uuids: []
    });
    let uuidFrom = reactive<UuidForm>({
        uuid: ''
    });
    const options = [
        {
            value: 1,
            label: 'Html',
        },
        {
            value: 2,
            label: 'Markdown',
        },
        {
            value: 3,
            label: 'Word',
        }
    ]

    const dbTypeOptions = [
        {
            value: 'MySQL',
            label: 'MySQL',
        }
    ]
    //获取form组件实例
    let form = ref<any>();
    //控制抽屉显示与隐藏
    let drawer = ref<boolean>(false);
    //收集新增岗位数据
    let datasourceAddOrUpdateForm = reactive<DatasourceAddOrUpdateForm>({
        uuid: '',
        connName: '',
        connUrl: '',
        dbType: '',
        environment: '',
        username: '',
        password: '',
        datasource: ''
    });

    let docGenForm = reactive<DocGenForm>({
        address: '',
        docType: 1,
        ignorePrefixList: [],
        ignoreSuffixList: [],
        ignoreTableNameList: [],
        uuid:''
    });
    //组件挂载完毕
    onMounted(() => {
        //获取职位请求
        getHasDatasource();
    });
    //获取全部用户信息的方法|分页器当前页码发生变化的回调
    const getHasDatasource = async (pager = 1) => {
        //修改当前页码
        page.value = pager;
        let result: DatasourceListReponseData = await reqDatasourcePageList(page.value-1, pageSize.value, datasourceLike.value,connNameLike.value);
        if (result.code == '200') {
            items.value = result.result.items;
            allDatasource.value = result.result.data;
        }
    }

    const findInfo = async (row: DatasourceInfo) => {
        drawer.value = true;
        //获取已有商品详情数据
        let result: DatasourceInfoReponseData = await reqDatasourceInfo(row.uuid);
        //存储已有的SKU
        datasourceInfo.value = result.result;
    }
    //下拉菜单的回调
    const sizeChange = () => {
        getHasDatasource();
    }
    //搜索按钮的回调
    const search = () => {
        //再次发请求根据关键字
        getHasDatasource();
        datasourceLike.value = '';
        connNameLike.value = '';
    }
    //重置按钮的回调
    const reset = () => {
        settingStore.refsh = !settingStore.refsh;
    }
    const setStatusButton = (row: any) =>{
        if (row.isOk =='1'){
            return 'success'
        } else {
            return 'danger'
        }
    }
    //添加职位按钮的回调
    const addDatasource = () => {
        //对话框显示出来
        dialogVisite.value = true;
        //清空数据
        Object.assign(datasourceAddOrUpdateForm, {
            connName: '',
            connUrl: '',
            dbType: '',
            environment: '',
            password: '',
            username: '',
            datasource: ''
        });
        //清空上一次表单校验错误结果
        nextTick(() => {
            form.value.clearValidate('roleName');
        })

    }

    //生成文档
    const genWordDatasource = (uuid) => {
        dialogDoc.value = true;

        //清空数据
        Object.assign(docGenForm, {
            address: '',
            docType: 1,
            ignorePrefixList: [],
            ignoreSuffixList: [],
            ignoreTableNameList: [],
            uuid:uuid
        });
    }

    const genWord = async () => {
        let result: HandleResponseData = await reqDatasourceGenWord(docGenForm);
        if (result.code == '200') {
            ElMessage({ type: 'success', message: '生成成功' });
        }else {
            ElMessage({ type: 'error', message: '生成失败'+result.msg });
        }
        dialogDoc.value = false;
        await getHasDatasource(page.value);
    }

    //更新已有的职位按钮的回调
    const updateDatasource = (row: RoleData) => {
        //显示出对话框
        dialogVisite.value = true;
        //存储已有的职位----带有ID的
        Object.assign(datasourceAddOrUpdateForm, row);
        //清空上一次表单校验错误结果
        nextTick(() => {
            form.value.clearValidate('roleName');
        })
    }
    //自定义校验规则的回调
    const validatorRoleName = (rule: any, value: any, callBack: any) => {
        if (value.trim().length >= 2) {
            callBack();
        } else {
            callBack(new Error('职位名称至少两位'))
        }
    }

    //职位校验规则
    const rules = {
        roleName: [
            {required: true, trigger: 'blur', validator: validatorRoleName}
        ],
        roleSort: [
            {required: true, trigger: 'blur'}
        ]
    }

    //确定按钮的回调
    const save = async () => {
        //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
        await form.value.validate();
        //添加职位|更新职位的请求
        let result: HandleResponseData = await reqAddOrUpdateDatasource(datasourceAddOrUpdateForm);
        if (result.code == '200') {
            //提示文字
            ElMessage({type: 'success', message: datasourceAddOrUpdateForm.uuid ? '更新成功' : '添加成功'});
        } else {
            ElMessage({type: 'error', message: datasourceAddOrUpdateForm.uuid ? '更新失败' + result.msg : '添加失败' + result.msg});
        }
        //对话框显示
        dialogVisite.value = false;
        //再次获取全部的已有的职位
        getHasDatasource(datasourceAddOrUpdateForm.uuid ? page.value : 0);

    }

    //测试连接
    const testConnect = async (uuid: string) => {
        let result: HandleResponseData = await reqDatasourceTestConnect(uuid);
        if (result.code == '200') {
            ElMessage({ type: 'success', message: '测试连接成功' });
        }else {
            ElMessage({ type: 'error', message: '测试连接失败'+result.msg });
        }
        await getHasDatasource(page.value);
    }

    //同步数据
    const syncData = async (uuid: string) => {
        let result: HandleResponseData = await reqDatasourceSync(uuid);
        if (result.code == '200') {
            ElMessage({ type: 'success', message: '同步数据成功' });
        }else {
            ElMessage({ type: 'error', message: '同步数据失败'+result.msg });
        }
        await getHasDatasource(page.value);
    }

    //删除已有的职位
    const delDatasource = async (uuid: string) => {
        uuidsFrom.uuids = [uuid]
        let result: HandleResponseData = await reqBatchDelDatasource(uuidsFrom);
        if (result.code == '200') {
            //提示信息
            ElMessage({type: 'success', message: '删除成功'});
        } else {
            ElMessage({type: 'error', message: '删除失败' + result.msg});

        }
        getHasDatasource(allDatasource.value.length > 1 ? page.value : page.value - 1);

    }
</script>

<style scoped>
    .form {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50px;
    }
</style>
